package com.hdaccp.hadoop.mr;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;

public class Music2CountApp {
    public static class Music2CountMapper extends Mapper<LongWritable,Text,Text,LongWritable>
    {
        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {

            String line = value.toString() ;
            String songName = line.split("\t")[0] ;
            /**
             * song1 1
             * song2 1
             * song3 1
             * song6 1
             * song6 1
             */
            context.write(new Text(songName),new LongWritable(1));


        }
    }

    public static class Music2Reduce extends Reducer<Text,LongWritable,Text,LongWritable>
    {
        /**
         * <song6,[1,1,1]></>
         * @param key
         * @param values
         * @param context
         * @throws IOException
         * @throws InterruptedException
         */
        @Override
        protected void reduce(Text key, Iterable<LongWritable> values, Context context) throws IOException, InterruptedException {
            long sum = 0 ;
            for(LongWritable w :values){
                sum = sum + w.get() ;
            }

            context.write(key,new LongWritable(sum));
        }
    }

    public static void main(String[] args) throws  Exception{
        if(args.length==0){
            System.err.print("没有传递参数！"); ;
            System.exit(1);
        }

        //1.core-site.xml
        Configuration cfg = new Configuration() ;

        Job job = Job.getInstance(cfg,"musice2mr") ;

        //配置job
        job.setJarByClass(Music2CountApp.class);
        //
        job.setMapperClass(Music2CountMapper.class);
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(LongWritable.class);
        FileInputFormat.setInputPaths(job,new Path(args[0]));

        job.setReducerClass(Music2Reduce.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(LongWritable.class);
        //如果hdfs上已经存在该文件
        Path pathout = new Path(args[1]) ;


        FileSystem fileSystem = FileSystem.get(cfg) ;
        if(fileSystem.exists(pathout)){
            fileSystem.delete(pathout,true) ;
        }

        FileOutputFormat.setOutputPath(job,pathout);

        System.exit(job.waitForCompletion(true)?0:1);
    }
}
